(function ($, undefined) {
    $.widget('ui.linqDataview', $.ui.dataview, {
        widgetEventPrefix: 'dataview',
        options: {
            paging: {
                limit: 10
            },
            resource: null,
            source: function (request, response) {
                var data = {
                    'skip': request.paging.offset,
                    'take': request.paging.limit
                };
                if (request.sort.length) {
                    var sorts = [];
                    $.each(request.sort, function (index, field) {
                        sorts[sorts.length] = field.replace(/-(.+)/, '$1 desc');
                    });
                    data['orderby'] = sorts.join(',');

                }
                if (request.filter) {
                    var filters = [];
                    $.each(request.filter, function (property, filter) {
                        if (filter.hasOwnProperty('Name')) {
                            filter = filter.Name;
                            property = property + '.Name';
                        }

                        if (!filter.operator) {
                            filter.operator = isNaN(filter.value) ? 'like' : '==';
                        }

                        if (filter.operator == 'like') {
                            filters[filters.length] = property + '.StartsWith("' + filter.value + '")';
                        } else {
                            var operators = {
                                '<': '<',
                                '<=': '<=',
                                '>': '>',
                                '>=': '>=',
                                '==': '=',
                                '!=': '!='
                            };
                            filters[filters.length] = property + " " + operators[filter.operator] + " " +
							(isNaN(filter.value) ? ('"' + filter.value + '"') : filter.value);
                        }

                    });
                    data['filter'] = filters.join(' AND ');
                }
                $.ajax({
                    url: request.resource,
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        response(data.rows, data.count);
                    }
                });
            }
        }
    });
} (jQuery));
